package com.oss.biz;

import cn.hutool.core.lang.Validator;
import cn.hutool.crypto.SecureUtil;
import com.eova.common.base.BaseController;
import com.jfinal.aop.Before;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Prop;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.oss.intercept.jwt.JWTInfo;
import com.oss.intercept.jwt.JWTUtil;
import com.oss.intercept.jwt.LoginInterceptor;
import com.oss.model.Employee;
import com.oss.service.DealerService;
import com.oss.service.EmployeeService;
import com.oss.service.UsersService;
import com.oss.utils.BaseContextHandler;
import com.oss.utils.constants.DataDictionary;
import com.oss.validator.employee.loginByEmployee;
import com.oss.validator.wxUser.userRegist;
import com.oss.view.InvokeResult;


public class UserController extends BaseController {

    JWTUtil jwtUtil = new JWTUtil();
    Prop prop = DataDictionary.getProp();

    static UsersService usersService = new UsersService();
    static EmployeeService employeeService = new EmployeeService();
    static DealerService dealerService = new DealerService();


    /**
     * 为每个门店创建账号
     */
    public void export() {
        renderJson(usersService.export());
    }

    /**
     * 授权登录
     */
    public void toOauth() {
        String calbackUrl = prop.get("domain") + "/oauth";
        String url = SnsAccessTokenApi.getAuthorizeURL(prop.get("appId"), calbackUrl, false);
        redirect(url);
    }

    /**
     * 模拟登录
     */
    public void simulatedLogin() {
        String accessToken = this.getCookie("access-token");

        if (accessToken != null) {
            this.setCookie("access-token", null, 0);
        }

        JWTInfo jwtInfo = new JWTInfo("菠萝油猴子", String.valueOf(1), "xzkjchkuahsdkjh");
        try {
            accessToken = jwtUtil.generateToken(jwtInfo);
        } catch (Exception e) {
            LogKit.info("token 生成失败：" + e);
        }

        this.setCookie("access-token", accessToken, DataDictionary.getProp().getInt("tokenExpired"));

        //跳转到注册页面
        //redirect(prop.get("regist_url"));
        renderJson(InvokeResult.success("模拟登录成功", accessToken));
    }

    /**
     * 新用户注册填写信息，并生成二维码
     */
    @Before({LoginInterceptor.class, userRegist.class})
    public void register() {
        String userId = BaseContextHandler.getUserID();
//        if (Validator.isEmpty(userId)) {
//            userId = "1";
//        }
        String name = this.getPara("name");
        Integer gender = this.getParaToInt("gender");
        String mobile = this.getPara("mobile");
        String province = this.getPara("province");
        String city = this.getPara("city");
        String region = this.getPara("region");
        String dealerId = this.getPara("dealerId");

        if (Validator.isNotEmpty(dealerId) && dealerId.equals("undefined")) {
            renderJson(InvokeResult.failure("请先选择注册门店"));
            return;
        }

        renderJson(usersService.register(userId, name, gender, mobile, province, city, region, Integer.valueOf(dealerId)));
    }

    @Before({LoginInterceptor.class})
    public void updateUserInfo() {
        String userId = BaseContextHandler.getUserID();
//        if (Validator.isEmpty(userId)) {
//            userId = "1";
//        }
        String mobile = this.getPara("mobile");
        String province = this.getPara("province");
        String city = this.getPara("city");
        String region = this.getPara("region");
        String detailAddress = this.getPara("detailAddress");
        renderJson(usersService.updateUserInfo(userId, mobile, province, city, region, detailAddress));
    }

    /**
     * 获取用户信息
     */
    @Before(LoginInterceptor.class)
    public void getUserInfo() {
        String userId = BaseContextHandler.getUserID();
        if (Validator.isEmpty(userId)) {
            userId = "1";
        }
        renderJson(usersService.getUserInfo(userId));
    }


    /**
     * 通过会员编码获取用户信息
     */
    public void getUserInfoByMemberCode() {
        String memberCode = this.getPara("memberCode");
        renderJson(usersService.getUserInfoByMemberCode(memberCode));
    }

    /**
     * 分页获取用户订单列表
     */
    @Before(LoginInterceptor.class)
    public void getUserOrderList() {
        String userId = BaseContextHandler.getUserID();
//        if (Validator.isEmpty(userId)) {
//            userId = "1";
//        }
        Integer pageNumber = this.getParaToInt("pageNumber", 1);
        Integer pageSize = this.getParaToInt("pageSize", 10);
        renderJson(usersService.getUserOrderList(userId, pageNumber, pageSize));
    }

    /**
     * 店员账号登录
     */
    @Before(loginByEmployee.class)
    public void loginByEmployee() {

        String accessToken = this.getCookie("access-token");
        if (accessToken != null) {
            this.setCookie("access-token", null, 0);
        }

        String account = this.getPara("account");
        String passWord = this.getPara("passWord");

        Employee employee = employeeService.loginByEmployee(account);
        if (Validator.isEmpty(employee)) {
            renderJson(InvokeResult.failure("账号不存在"));
            return;
        }
        if (!employee.getPassword().equals(SecureUtil.md5(passWord))) {
            renderJson(InvokeResult.failure("密码错误"));
            return;
        }

        JWTInfo jwtInfo = new JWTInfo(employee.getAccount(), String.valueOf(employee.getId()), employee.getAccount());
        try {
            accessToken = jwtUtil.generateToken(jwtInfo);
        } catch (Exception e) {
            LogKit.info("token 生成失败：" + e);
        }

        this.setCookie("access-token", accessToken, DataDictionary.getProp().getInt("tokenExpired"));

        renderJson(InvokeResult.success("登录成功", null));
    }


    //    @Before(LoginInterceptor.class)
    public void getEmployeeInfo() {
        String employeeId = BaseContextHandler.getUserID();
        if (Validator.isEmpty(employeeId)) {
            employeeId = "1";
        }
        renderJson(employeeService.findById(employeeId));
    }

}
